﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Configuration;

using System.Web.Security;

using Ample.Model;

/// <summary>
/// Summary description for CustomMembershipProvider
/// </summary>
/// 

namespace Ample.DAL
{
    public class CustomMembershipProvider : System.Web.Security.SqlMembershipProvider
    {
        public CustomMembershipProvider()
            : base()
        {
            //
            // TODO: Add constructor logic here
            //
        }

        public override System.Web.Security.MembershipUser CreateUser(string username, string password, string email, string passwordQuestion, string passwordAnswer, bool isApproved, object providerUserKey, out System.Web.Security.MembershipCreateStatus status)
        {
            username = GetUsername(ConfigurationManager.ConnectionStrings["AmpleDBDefConStr"].ConnectionString);

            MembershipUser mu = base.CreateUser(username, password, email, passwordQuestion, passwordAnswer,
                                 isApproved, providerUserKey, out status);

            return mu;
        }

        public string GetUsername(string connString)
        {
            string username = "10000";

            using (AmpleDataContext adc = new AmpleDataContext(connString))
            {
                IOrderedQueryable<Aspnet_Membership> iam = adc.Aspnet_Memberships.OrderByDescending(a => a.CreateDate);

                foreach (Aspnet_Membership am in iam)
                {
                    username =
                        adc.Users.Where(c => c.Aspnet_Membership.CreateDate == am.CreateDate).Select(a => a.UserName).
                            Max();

                    int temp = -1;

                    if (!Int32.TryParse(username, out temp) || string.IsNullOrEmpty(username))
                    {
                        username = "10000";
                        continue;
                    }

                    username = (++temp).ToString();
                    break;
                }
            }

            return username;
        }
    }
}